const Model3D = require('../models/modelModel');
const path = require('path');
const fileUtils = require('../utils/fileUtils');
const fs = require('fs-extra');
const config = require('../config/config');

/**
 * 获取用户的所有模型
 */
exports.getAllModels = async (userId) => {
    try {
        const models = await Model3D.find({ userId })
            .select('_id name description geometry additionalObjects createdAt thumbnail')
            .sort({ createdAt: -1 });

        // 转换为前端所需格式，确保id字段存在
        const formattedModels = models.map(model => {
            const modelObj = model.toObject();
            modelObj.id = modelObj._id.toString(); // 确保id字段有值
            return modelObj;
        });

        return { success: true, data: formattedModels };
    } catch (error) {
        return { success: false, error: error.message };
    }
};

/**
 * 创建新模型
 */
exports.createModel = async (modelData, userId) => {
    try {
        const newModel = new Model3D({
            ...modelData,
            userId
        });

        const savedModel = await newModel.save();

        // 返回更完整的模型信息
        const modelObj = savedModel.toObject();

        return {
            success: true,
            data: {
                model: {
                    id: modelObj._id.toString(),
                    _id: modelObj._id,
                    name: modelObj.name,
                    description: modelObj.description,
                    geometry: modelObj.geometry,
                    additionalObjects: modelObj.additionalObjects || []
                },
                message: '模型创建成功'
            }
        };
    } catch (error) {
        return { success: false, error: error.message };
    }
};

/**
 * 更新模型信息
 */
exports.updateModel = async (modelId, userId, updateData) => {
    try {
        // 确保只有模型所有者可以更新
        const updatedModel = await Model3D.findOneAndUpdate(
            { _id: modelId, userId },
            updateData,
            { new: true }
        );

        if (!updatedModel) {
            return { success: false, error: '模型不存在或无权限修改' };
        }

        return { success: true, message: '模型信息更新成功' };
    } catch (error) {
        return { success: false, error: error.message };
    }
};

/**
 * 删除模型
 */
exports.deleteModel = async (modelId, userId) => {
    try {
        // 先获取模型信息，以便删除关联文件
        const model = await Model3D.findOne({ _id: modelId, userId });

        if (!model) {
            return { success: false, error: '模型不存在或无权限删除' };
        }

        // 删除模型文件（如果存在）
        if (model.file && model.file.filePath) {
            await fileUtils.deleteFile(model.file.filePath);
        }

        // 删除缩略图（如果存在）
        if (model.thumbnail && model.thumbnail.path) {
            await fileUtils.deleteFile(model.thumbnail.path);
        }

        // 删除整个模型目录
        const modelStoragePath = path.join(config.storage.basePath, userId.toString(), modelId.toString());
        if (await fs.pathExists(modelStoragePath)) {
            await fs.remove(modelStoragePath);
        }

        // 删除数据库记录
        await Model3D.deleteOne({ _id: modelId, userId });

        return { success: true, message: '模型及关联文件已删除' };
    } catch (error) {
        return { success: false, error: error.message };
    }
};

/**
 * 根据ID获取模型
 */
exports.getModelById = async (modelId, userId) => {
    try {
        const model = await Model3D.findOne({ _id: modelId, userId });

        if (!model) {
            return { success: false, error: '模型不存在或无权限访问' };
        }

        // 转换为前端所需格式
        const modelObj = model.toObject();
        modelObj.id = modelObj._id.toString(); // 确保id字段有值

        return { success: true, data: modelObj };
    } catch (error) {
        return { success: false, error: error.message };
    }
}; 